<?php

declare(strict_types=1);

namespace app\category\controller;

use app\BaseController;
use app\model\AttributeName;
use app\model\AttributeValue;
use app\model\Goods;
use app\category\model\Category;
use app\model\SkuCategory;

class Sub extends BaseController
{
    /**
     * 根据二级id查所属的商品信息以及sku
     * @param id $id
     * @return void
     */
    public function index()
    {
        // 接收用户传过来的分类id
        $sub_id = $this->request->param('id') ? $this->request->param('id') : null;
        if ($sub_id) {
            $DBGoods = new Goods();
            // 根据id查找该id下的商品信息
            $goodsList = $DBGoods->where('cid', $sub_id)->field('goods_id,cid,goods_name,goods_picture,goods_price,goods_discount')->select();
            $DBAName = new AttributeName();
            $DBAValue = new AttributeValue();
            // 查找二级分类对应的sku的键
            $NameInfo = $DBAName->where('cid', $sub_id)->select();
            $skuList = [];
            // 根据skuValue表的值进行循环
            foreach ($NameInfo as $value) {
                $sku = $DBAValue->where('attribute_id', $value->id)->field('attribute_value')->select()->toArray();
                $skuList[$value->attribute_name] = $sku;
            }
            // 根据id查找该id父级信息
            $DBSkuCategory = new SkuCategory();
            $SkuCInfo = $DBSkuCategory->where('id', $sub_id)->select()->toArray();
            $data = ['goods' => $goodsList, 'sku' => $skuList, 'info' => $SkuCInfo[0]];
            return result($data);
        } else {
            $DBcategory = new Category();
            // 查找分类里的商品，并携带一级id 
            $result = $DBcategory->where('goods_id', '<>', 'null')->field('pid,goods_id,goods_name,goods_picture,goods_price,goods_desc,goods_discount')->select();
            return result($result);
        }
    }
    public function find()
    {
        $page = $this->request->param('page');
        $DBcategory = new Category();
        $info = $DBcategory->where('children_id', '<>', 'null')->page($page, 11)->select();
        $count = $DBcategory->where('children_id', '<>', 'null')->count();
        return result(['sub' => $info, 'count' => $count]);
    }
}
